package com.jingdun.sport.api.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingdun.sport.bean.model.*;
import com.jingdun.sport.security.util.SecurityUtils;
import com.jingdun.sport.service.*;
import com.jingdun.sport.utils.kuaidi100;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/sport/prizeWidgetRelation/")
@Api(tags = "奖品部件关联关系接口")
@Slf4j
public class PrizeWidgetRelationController {

    @Autowired
    private PrizeWidgetRelationService prizeWidgetRelationService;

    @Autowired
    private PrizesService prizesService;

    @Autowired
    private UserPrizeWidgetRelationService userPrizeWidgetRelationService;

    @Autowired
    private SyntheticPrizeService syntheticPrizeService;

    @Autowired
    private UserDeliveryService userDeliveryService;

    @Autowired
    private DeliveryService deliveryService;

    @Autowired
    private TrendsService trendsService;

    @Autowired
    private TrendsPicsService trendsPicsService;

    /**
     * 新建奖品部件关联关系接口
     */
    @PostMapping("/addPrizeWidgetRelation")
    @ApiOperation(value = "新建奖品部件关联关系接口", notes = "新建奖品部件关联关系接口")
    public ResponseEntity<ApiResult> addPrizeWidgetRelation(@RequestBody PrizeWidgetRelation prizeWidgetRelation) {
        //部件名称相同 CASE 1 prizeId相同 widgetName相同 不能新增
        //部件编号相同 CASE 2 prizeId相同 widgetNumber相同 不能新增
        Map m = new HashMap<String, Object>();
        //重复检查类型 1:新增, 2:修改
        m.put("duplicateCheckType", "2");
        m.put("prizeId", prizeWidgetRelation.getPrizeId());
        m.put("widgetName", prizeWidgetRelation.getWidgetName());
        m.put("widgetNumber", prizeWidgetRelation.getWidgetNumber());
        List<PrizeWidgetRelation> list = prizeWidgetRelationService.getPrizeWidgetRelationDuplicateCheckList(m);
        ApiResult apiResult = new ApiResult();
        if (list.size() == 0) {
            prizeWidgetRelationService.addPrizeWidgetRelation(prizeWidgetRelation);
            //return ResponseEntity.ok().build();
        } else {
            //return ResponseEntity.ok("部件名称或部件编号不能重复");
            apiResult.setMsg("部件名称或部件编号不能重复");
        }
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 获取抽奖结果，获取随机奖品部件关联关系详情接口
     */
    @GetMapping("/getRandomPrizeWidgetRelationDetail")
    @ApiOperation(value = "获取随机奖品部件关联关系详情接口", notes = "获取随机奖品部件关联关系详情接口")
    public ApiResult getRandomPrizeWidgetRelationDetail() {
        // TODO: 2020-08-27  判断用户是否具备获取奖励的条件
        Map m = new HashMap<String, Object>();
        List<Map<String, Object>> prizeWidgetRelationIdList = prizeWidgetRelationService.getPrizeWidgetRelationIdList(m);
        Random rand = new Random();
        int nextRandomInt = rand.nextInt(501);
        Long id = 0l;
//        设计成最后两个获取的概率是五百分之一
        if (nextRandomInt < 1) {
//            prizeWidgetRelationIdList.size() - 2 + nextRandomInt，获取最后两个中的随机一个中奖
            nextRandomInt = rand.nextInt(2);
            id = Long.parseLong((prizeWidgetRelationIdList.get(prizeWidgetRelationIdList.size() - 2 + nextRandomInt)).get("id").toString());
        } else {
            nextRandomInt = rand.nextInt(prizeWidgetRelationIdList.size() - 2);
            id = Long.parseLong((prizeWidgetRelationIdList.get(nextRandomInt)).get("id").toString());
        }
        m.put("id", id);
        PrizeWidgetRelation prizeWidgetRelation = prizeWidgetRelationService.getPrizeWidgetRelationDetail(m);
        PrizeWidgetRelationResponse prizeWidgetRelationResponse = new PrizeWidgetRelationResponse();
        BeanUtils.copyProperties(prizeWidgetRelation, prizeWidgetRelationResponse);
        ApiResult apiResult = new ApiResult();
        Prizes prizes = prizesService.getById(prizeWidgetRelation.getPrizeId());
        if (prizes != null) {
            prizeWidgetRelationResponse.setPrizePic(prizes.getPic());
        }
//        数量
        prizeWidgetRelationResponse.setWidgetNumber(1);
        UserPrizeWidgetRelation userPrizeWidgetRelation = new UserPrizeWidgetRelation();
        userPrizeWidgetRelation.setUserId(SecurityUtils.getUser().getUserId());
        userPrizeWidgetRelation.setPrizeWidgetId(prizeWidgetRelation.getId());
        userPrizeWidgetRelation.setPrizeId(prizeWidgetRelation.getPrizeId());
        userPrizeWidgetRelationService.addUserPrizeWidgetRelation(userPrizeWidgetRelation);
        apiResult.setData(prizeWidgetRelationResponse);
        return apiResult;
    }

    /**
     * 获取奖品部件关联关系详情接口
     */
    @GetMapping("/getPrizeWidgetRelationDetail")
    @ApiOperation(value = "获取奖品部件关联关系详情接口", notes = "获取奖品部件关联关系详情接口")
    public ApiResult getPrizeWidgetRelationDetail(long id) {
        Map m = new HashMap<String, Object>();
        m.put("id", id);
        PrizeWidgetRelation prizeWidgetRelation = prizeWidgetRelationService.getPrizeWidgetRelationDetail(m);
        //return prizeWidgetRelation;
        ApiResult apiResult = new ApiResult();
        apiResult.setData(prizeWidgetRelation);
        return apiResult;
    }

    /**
     * 删除奖品部件关联关系接口
     */
    @PostMapping("/removePrizeWidgetRelation")
    @ApiOperation(value = "删除奖品部件关联关系接口", notes = "删除奖品部件关联关系接口")
    public ResponseEntity removePrizeWidgetRelation(long id) {
        PrizeWidgetRelation prizeWidgetRelation = new PrizeWidgetRelation();
        prizeWidgetRelation.setId(id);
        prizeWidgetRelation.setEnabled("0");
        prizeWidgetRelationService.updatePrizeWidgetRelation(prizeWidgetRelation);
        ApiResult apiResult = new ApiResult();
        //return ResponseEntity.ok().build();
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 修改奖品部件关联关系接口
     */
    @PostMapping("/updatePrizeWidgetRelation")
    @ApiOperation(value = "修改奖品部件关联关系接口", notes = "修改奖品部件关联关系接口")
    public ResponseEntity updatePrizeWidgetRelation(@RequestBody PrizeWidgetRelation prizeWidgetRelation) {
        //修改的业务比新增复杂一些
        //部件名称相同 CASE 1 prizeId相同 widgetName相同   奖品部件关联关系id相同 不冲突 能修改
        //部件编号相同 CASE 2 prizeId相同 widgetNumber相同 奖品部件关联关系id相同 不冲突 能修改
        //部件名称相同 CASE 3 prizeId相同 widgetName相同   奖品部件关联关系id不同 冲突 不能修改
        //部件编号相同 CASE 4 prizeId相同 widgetNumber相同 奖品部件关联关系id不同 冲突 不能修改
        Map m = new HashMap<String, Object>();
        //重复检查类型 1:新增, 2:修改
        m.put("duplicateCheckType", "2");
        m.put("id", prizeWidgetRelation.getId());
        m.put("prizeId", prizeWidgetRelation.getPrizeId());
        m.put("widgetName", prizeWidgetRelation.getWidgetName());
        m.put("widgetNumber", prizeWidgetRelation.getWidgetNumber());
        List<PrizeWidgetRelation> list = prizeWidgetRelationService.getPrizeWidgetRelationDuplicateCheckList(m);
        ApiResult apiResult = new ApiResult();
        if (list.size() == 0) {
            prizeWidgetRelationService.updatePrizeWidgetRelation(prizeWidgetRelation);
            //return ResponseEntity.ok().build();
        } else {
            //return ResponseEntity.ok("部件名称或部件编号不能重复");
            apiResult.setMsg("部件名称或部件编号不能重复");
        }
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 分页获取奖品部件关联关系接口
     */
    @RequestMapping("/getPaginationPrizeWidgetRelation")
    @ApiOperation(value = "分页获取奖品部件关联关系接口", notes = "分页获取奖品部件关联关系接口")
    public ResponseEntity<ApiResult> getPaginationPrizeWidgetRelation(long size, long current) {
        Map m = new HashMap<String, Object>();
        m.put("size", size);
        m.put("current", current);
        Page<Map<String, Object>> page = prizeWidgetRelationService.getPaginationPrizeWidgetRelation(m);
        //return ResponseEntity.ok(page);
        ApiResult apiResult = new ApiResult();
        apiResult.setData(page);
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 合成接口
     */
    @RequestMapping("/synthetic")
    @ApiOperation(value = "合成奖品的接口", notes = "合成奖品的接口")
    public ResponseEntity synthetic(Long prizeId) {
//        1、从prizes，prize_widget_relation，user_prize_widget_relation三张表中判断用户是否满足合成的条件
        Prizes prizes = prizesService.getById(prizeId);
        LambdaQueryWrapper<PrizeWidgetRelation> prizeWidgetRelationLambdaQueryWrapper = new LambdaQueryWrapper<PrizeWidgetRelation>()
                .eq(PrizeWidgetRelation::getPrizeId, prizeId).eq(PrizeWidgetRelation::getEnabled, 1);
        List<PrizeWidgetRelation> prizeWidgetRelationList = prizeWidgetRelationService.list(prizeWidgetRelationLambdaQueryWrapper);
        if (prizeWidgetRelationList == null || prizeWidgetRelationList.isEmpty()) {
            return ResponseEntity.status(203).body("无此奖品类型");
        }
        List<PareGetMyPackageDataListResponse> myPackageDataList = userPrizeWidgetRelationService.getMyPackageDataList(SecurityUtils.getUser().getUserId());
        if (myPackageDataList == null || myPackageDataList.isEmpty()) {
            return ResponseEntity.ok("用户无奖品可合成");
        }
        PareGetMyPackageDataListResponse pareGetMyPackageDataListResponse = myPackageDataList.stream().filter(myPackageData -> myPackageData.getPrizeId() == prizeId).findFirst().orElse(null);
        if (pareGetMyPackageDataListResponse == null) {
            return ResponseEntity.ok("用户无该奖品的组件");
        }
        List<GetMyPackageDataListResponse> prizeWidgetList = pareGetMyPackageDataListResponse.getPrizeWidgetList();
        Set<Long> userPrizeWidgetSet = prizeWidgetList.stream().map(prizeWidget -> {
            return prizeWidget.getPrizeWidgetId();
        }).collect(Collectors.toSet());
        Set<Long> prizeWidgetSet = prizeWidgetRelationList.stream().map(prizeWidgetRelation -> {
            return prizeWidgetRelation.getId();
        }).collect(Collectors.toSet());
        boolean sign = true;
        for (Long prizeWidgetId : prizeWidgetSet) {
            if (!userPrizeWidgetSet.contains(prizeWidgetId)) {
                sign = false;
                break;
            }
        }
        if (!sign) {
            return ResponseEntity.ok("用户无合成该奖品");
        } else {
//        2、满足则在synthetic_prize表中插入一条记录，status字段为0
            Set<Long> hasDeleteWidgetId = new HashSet<>();
            boolean update = true;
            for (PrizeWidgetRelation prizeWidgetRelation : prizeWidgetRelationList) {
                if (!hasDeleteWidgetId.contains(prizeWidgetRelation.getId())) {
                    LambdaQueryWrapper<UserPrizeWidgetRelation> userPrizeWidgetRelationLambdaQueryWrapper = new LambdaQueryWrapper<UserPrizeWidgetRelation>()
                            .eq(UserPrizeWidgetRelation::getPrizeWidgetId, prizeWidgetRelation.getId())
                            .and(wrapper1 -> wrapper1.eq(UserPrizeWidgetRelation::getUserId, SecurityUtils.getUser().getUserId()))
                            .and(wrapper2 -> wrapper2.eq(UserPrizeWidgetRelation::getEnabled, 1));
                    List<UserPrizeWidgetRelation> userPrizeWidgetRelationList = userPrizeWidgetRelationService.list(userPrizeWidgetRelationLambdaQueryWrapper);
                    if (userPrizeWidgetRelationList != null && !userPrizeWidgetRelationList.isEmpty()) {
                        UserPrizeWidgetRelation userPrizeWidgetRelation = userPrizeWidgetRelationList.get(0);
                        userPrizeWidgetRelation.setEnabled("0");
                        boolean b = userPrizeWidgetRelationService.updateById(userPrizeWidgetRelation);
                        if (b) {
                            log.info("清除用户组件成功{}", prizeWidgetRelation.getId());
                            hasDeleteWidgetId.add(prizeWidgetRelation.getId());
                        } else {
                            update = false;
                            break;
                        }
                    } else {
                        update = false;
                        break;
                    }
                }
            }
            if (update) {
//                插入一条合成奖品记录
                SyntheticPrize syntheticPrize = new SyntheticPrize();
                syntheticPrize.setCreateTime(new Date());
                syntheticPrize.setDeleted(0);
                syntheticPrize.setPrizeId(prizeId);
                syntheticPrize.setPrizeName(prizes.getName());
                syntheticPrize.setPrizePic(prizes.getPic());
                syntheticPrize.setStatus(0);
                syntheticPrize.setUserId(SecurityUtils.getUser().getUserId());
                syntheticPrizeService.save(syntheticPrize);
                Trends trends = new Trends();
                trends.setUserId(SecurityUtils.getUser().getUserId());
                trends.setContent("今天在斑马运动喜提" + prizes.getName() + "，赶快来运动吧，您也可以赢得宝箱大奖！");
                trends.setEnable(1);
                trends.setType(0);
                trendsService.save(trends);
                TrendsPics trendsPics = new TrendsPics();
                trendsPics.setEnable(1);
                trendsPics.setPicUrl(prizes.getPic());
                trendsPics.setTrendsId(trends.getId());
                trendsPicsService.save(trendsPics);
                return ResponseEntity.ok(ApiResult.getInstance().setCode(200).setData(syntheticPrize.getId()));
            }
        }
        return ResponseEntity.ok(ApiResult.getInstance().setCode(203).setData("合成异常"));
    }

    /**
     * 奖品领取接口
     */
    @RequestMapping("/getStuff")
    @ApiOperation(value = "奖品领取接口", notes = "奖品领取接口")
    public ResponseEntity getStuff(Long syntheticPrizeId, String trackingName, String trackingMobile, String address) {
//        变更synthetic_prize表中对应的status字段状态为1，及相关的收货人信息，
        LambdaQueryWrapper<SyntheticPrize> syntheticPrizeLambdaQueryWrapper = new LambdaQueryWrapper<SyntheticPrize>()
                .eq(SyntheticPrize::getId, syntheticPrizeId).eq(SyntheticPrize::getUserId, SecurityUtils.getUser().getUserId());
        SyntheticPrize syntheticPrize = syntheticPrizeService.getOne(syntheticPrizeLambdaQueryWrapper);
        if (syntheticPrize == null) {
            return ResponseEntity.ok().body(ApiResult.getInstance().setCode(203).setData("该用户无此奖品"));
        }
        LambdaUpdateWrapper<SyntheticPrize> syntheticPrizeLambdaUpdateWrapper = new LambdaUpdateWrapper<SyntheticPrize>()
                .eq(SyntheticPrize::getId, syntheticPrizeId)
                .set(SyntheticPrize::getStatus, 1)
                .set(SyntheticPrize::getTrackingName, trackingName)
                .set(SyntheticPrize::getTrackingMobile, trackingMobile)
                .set(SyntheticPrize::getTrackingAddress, address);
        boolean update = syntheticPrizeService.update(syntheticPrizeLambdaUpdateWrapper);
        if (update) {
            return ResponseEntity.ok(ApiResult.getInstance());
        } else {
            return ResponseEntity.ok().body(ApiResult.getInstance().setCode(203).setData("领取失败"));
        }
    }

    /**
     * 奖品合成记录接口
     */
    @RequestMapping("/prizeSyntheticLogList")
    @ApiOperation(value = "奖品合成记录接口", notes = "奖品合成记录接口")
    public ResponseEntity<ApiResult> prizeSyntheticLogList(long size, long current) {
//        从synthetic_prize表中查询对应的合成记录的数据
        Map m = new HashMap<String, Object>();
        m.put("size", size);
        m.put("current", current);
        IPage iPage = new Page();
        iPage.setSize(size);
        iPage.setCurrent(current);
        IPage page = syntheticPrizeService.page(iPage);
        ApiResult apiResult = new ApiResult();
        apiResult.setData(page);
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 合成奖品发货接口
     */
    @RequestMapping("/prizeDeliver")
    @ApiOperation(value = "合成奖品发货接口", notes = "合成奖品发货接口")
    public ResponseEntity prizeDeliver(String logisticsCompanyName, String logisticsCompanyCode, String logisticsNum, Long syntheticPrizeId) {
        LambdaUpdateWrapper<SyntheticPrize> syntheticPrizeLambdaUpdateWrapper = new LambdaUpdateWrapper<SyntheticPrize>()
                .eq(SyntheticPrize::getId, syntheticPrizeId)
                .set(SyntheticPrize::getStatus, 2)
                .set(SyntheticPrize::getTrackingNumber, logisticsNum)
                .set(SyntheticPrize::getTrackingCode, logisticsCompanyCode);
        boolean update = syntheticPrizeService.update(syntheticPrizeLambdaUpdateWrapper);
        if (update) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.ok().body(ApiResult.getInstance().setCode(203).setData("领取失败"));
        }
    }

    /**
     * 查看物流信息接口
     */
    @RequestMapping("/trackingInfo")
    @ApiOperation(value = "查看物流信息接口", notes = "查看物流信息接口")
    public ResponseEntity logisticsInfo(Long syntheticPrizeId) {
        SyntheticPrize syntheticPrize = syntheticPrizeService.getById(syntheticPrizeId);
//        Date date = new Date();//取时间
//        Calendar calendar = new GregorianCalendar();
//        calendar.setTime(date);
//        calendar.add(Calendar.HOUR, -12);//把日期往前减少一天，若想把日期向后推一天则将负数改为正数
//        date = calendar.getTime();
//        Date finalDate = date;
//        if (syntheticPrize.getUpdateTime().compareTo(finalDate) < 0) {
        List<Map<String, Object>> maps = kuaidi100.rightKuaidi100(syntheticPrize.getTrackingNumber(), syntheticPrize.getTrackingCode());
        String address = JSON.toJSONString(maps);
        LambdaUpdateWrapper<SyntheticPrize> syntheticPrizeLambdaUpdateWrapper = new LambdaUpdateWrapper<SyntheticPrize>()
                .eq(SyntheticPrize::getId, syntheticPrizeId)
                .eq(SyntheticPrize::getDeleted, 0)
                .set(SyntheticPrize::getTrackingInfo, address);
        boolean update = syntheticPrizeService.update(syntheticPrizeLambdaUpdateWrapper);
        if (update) {
            syntheticPrize.setTrackingInfo(address);
            return ResponseEntity.ok().body(ApiResult.getInstance().setData(syntheticPrize));
        }
//        }
        return ResponseEntity.ok().body(ApiResult.getInstance().setData(syntheticPrize));
    }

    /**
     * 确认收货接口
     */
    @RequestMapping("/confirmReceipt")
    @ApiOperation(value = "确认收货接口", notes = "确认收货接口")
    public ResponseEntity confirmReceipt(Long syntheticPrizeId) {
        LambdaQueryWrapper<SyntheticPrize> syntheticPrizeLambdaQueryWrapper = new LambdaQueryWrapper<SyntheticPrize>()
                .eq(SyntheticPrize::getId, syntheticPrizeId)
                .eq(SyntheticPrize::getUserId, SecurityUtils.getUser().getUserId())
                .eq(SyntheticPrize::getStatus, 3);
        SyntheticPrize syntheticPrize = syntheticPrizeService.getById(syntheticPrizeId);
        if (syntheticPrize == null) {
            return ResponseEntity.ok().body(ApiResult.getInstance().setCode(203).setData("该奖品不能确认收货"));
        }
        LambdaUpdateWrapper<SyntheticPrize> syntheticPrizeLambdaUpdateWrapper = new LambdaUpdateWrapper<SyntheticPrize>()
                .eq(SyntheticPrize::getId, syntheticPrizeId)
                .set(SyntheticPrize::getStatus, 3);
        boolean update = syntheticPrizeService.update(syntheticPrizeLambdaUpdateWrapper);
        if (update) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.ok().body(ApiResult.getInstance().setCode(203).setData("确认收货失败失败"));
        }
    }

    /**
     * 获取物流公司信息接口
     */
    @RequestMapping("/logisticsCompanyList")
    @ApiOperation(value = "获取物流公司信息接口", notes = "获取物流公司信息接口")
    public ResponseEntity<ApiResult> logisticsCompanyList() {
        List<Delivery> deliveryList = deliveryService.list();
        ApiResult apiResult = new ApiResult();
        apiResult.setData(deliveryList);
        return ResponseEntity.ok(apiResult);
    }
}